package com.xiaozhengkeji.blogsuper.api;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.xiaozhengkeji.blogsuper.base.entitys.UserEntity;
import com.xiaozhengkeji.blogsuper.base.service.UserEntityService;
import com.xiaozhengkeji.blogsuper.bean.ResponseBean;
import com.xiaozhengkeji.blogsuper.bean.type.ResCodeType;
import com.xiaozhengkeji.blogsuper.services.EMailService;
import com.xiaozhengkeji.blogsuper.services.bus.UserServiceBus;
import com.xiaozhengkeji.blogsuper.utils.AddressesUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import wiki.xsx.core.util.RedisUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * 用户Api
 */
@Slf4j
@RestController
@RequestMapping("/web/user")
public class UserApi {

    @Autowired
    UserEntityService userEntityService;
    @Autowired
    UserServiceBus userServiceBus;
    @Autowired
    EMailService eMailService;


    /**
     * 用户注册
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public ResponseBean register(@ApiParam("用户名") @RequestParam("username") String username,
                                 @ApiParam("邮箱") @RequestParam("mailbox") String mailbox,
                                 @ApiParam("密码") @RequestParam("password") String password,
                                 @ApiParam("邮箱验证码") @RequestParam("mailboxcode") String mailboxcode,
                                 HttpServletRequest request) {
        String redis_verificationCode = RedisUtil.getStringHandler(32).get("Register_" + mailbox);
        if (!redis_verificationCode.equalsIgnoreCase(mailboxcode)) {
            return new ResponseBean(ResCodeType.Error, "验证码错误!", null, 1);
        }
        int ret = userServiceBus.register(username, mailbox, password, AddressesUtil.getIpAddress(request));
        if (ret == 1) {
            RedisUtil.getStringHandler(32).remove("Register_" + mailbox);
            return new ResponseBean(ResCodeType.Success, "注册成功!", ret, null);
        } else {
            return new ResponseBean(ResCodeType.Error, "注册失败!服务器错误", ret, 2);
        }
    }

    /**
     * 发送注册验证硬件
     */
    @ApiOperation("发送注册用邮件")
    @GetMapping("/register/sendEMail")
    public ResponseBean sendEMail(@ApiParam("用户名") @RequestParam("username") String username,
                                  @ApiParam("邮箱") @RequestParam("mailbox") String mailbox,
                                  @ApiParam("获取图片验证码时提交的时间戳") @RequestParam("verificationCodeTag") String verificationCodeTag,
                                  @ApiParam("图片验证码的验证码") @RequestParam("verificationCode") String verificationCode) {
        String redis_gcv = RedisUtil.getStringHandler(31).get("GVC_" + verificationCodeTag);
        if (!redis_gcv.equalsIgnoreCase(verificationCode)) {
            return new ResponseBean(ResCodeType.Error, "验证码错误!", null, 2);
        }
        RedisUtil.getStringHandler(31).remove("GVC_" + verificationCodeTag);
        List<UserEntity> userEntity = userEntityService.queryByEMailBox(mailbox);
        if (userEntity.size() > 0) {
            return new ResponseBean(ResCodeType.Error, "邮箱已被注册!", null, 1);
        }
        if (RedisUtil.getStringHandler(32).get("Register_" + mailbox) != null) {
            return new ResponseBean(ResCodeType.Error, "已发送过验证码!", null, 3);
        }
        String emailBox_VerificationCode = RandomUtil.randomString(5).toUpperCase(Locale.ROOT);
        eMailService.sendRegisterEMail(mailbox, username, emailBox_VerificationCode);
        RedisUtil.getStringHandler(32).set("Register_" + mailbox, emailBox_VerificationCode, 60 * 10, TimeUnit.SECONDS);
        return new ResponseBean(ResCodeType.Success, "已发送验证码!请在10分钟内完成注册!", null, null);
    }

    /**
     * 用户登录
     */
    @ApiOperation("登录")
    @PostMapping("login")
    public ResponseBean login(@ApiParam("邮箱") @RequestParam("mailbox") String mailbox,
                              @ApiParam("密码") @RequestParam("password") String password,
                              @ApiParam("获取图片验证码时提交的时间戳") @RequestParam("verificationCodeTag") String verificationCodeTag,
                              @ApiParam("图片验证码的验证码") @RequestParam("verificationCode") String verificationCode,
                              HttpServletRequest request) {
        String redis_gcv = RedisUtil.getStringHandler(31).get("GVC_" + verificationCodeTag);
        if (redis_gcv == null){
            return new ResponseBean(ResCodeType.Error, "验证码过期!", null, 3);
        }
        if (!redis_gcv.equalsIgnoreCase(verificationCode)) {
            return new ResponseBean(ResCodeType.Error, "验证码错误!", null, 2);
        }
        RedisUtil.getStringHandler(31).remove("GVC_" + verificationCodeTag);
        List<UserEntity> user_entity_Base = userEntityService.queryByEMailBoxAndPassWord(mailbox, password);
        if (user_entity_Base.size() < 1) {
            return new ResponseBean(ResCodeType.Error, "用户名或密码错误!", null, 1);
        }
        StpUtil.setLoginId(user_entity_Base.get(0).getId());
        return new ResponseBean(ResCodeType.Success, "登录成功", StpUtil.getTokenInfo(), StpUtil.getTokenInfo().tokenValue);
    }


    /**
     * 验证Token的有效性
     */
    @ApiOperation("验证Token的有效性")
    @GetMapping("verifyToken")
    public ResponseBean verifyToken(@RequestParam("Token") String Token) {
        if (StpUtil.getLoginIdByToken(Token) == null) {
            return new ResponseBean(ResCodeType.Error, "Token过期!", null, null);
        }
        Integer loginID = Integer.parseInt((String) StpUtil.getLoginIdByToken(Token));
        UserEntity userEntity = userEntityService.selectByPrimaryKey(loginID);
        return new ResponseBean(ResCodeType.Success, "自动登录成功!", userEntity.getEMailBox(), null);
    }


}
